package com.laopan.elasticsearch.bean.geo;


import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

/**
 * 坐标信息
 *
 * @author laopan
 * @className LocationEsEntity
 * @date 2021/3/9 16:55
 */
public class Location {
    /**
     * 经度
     */
    private Double lon;
    /**
     * 纬度
     */
    private Double lat;

    public Location() {

    }

    public Location(Double lon, Double lat) {
        this.lon = lon;
        this.lat = lat;
    }

    public Double getLon() {
        return lon;
    }

    public void setLon(Double lon) {
        this.lon = lon;
    }

    public Double getLat() {
        return lat;
    }

    public void setLat(Double lat) {
        this.lat = lat;
    }

    public GeoPoint convertGeoPoint() {
        return new GeoPoint(getLat(), getLon());
    }

    public GeoDistanceSortBuilder geoSortBuilder(String fieldName) {
        if (null != getLat() && null != getLon()) {
            return SortBuilders.geoDistanceSort(fieldName, getLat(), getLon())
                    .unit(DistanceUnit.METERS)
                    .order(SortOrder.ASC);
        }
        return null;
    }

    public GeoDistanceQueryBuilder geoQueryBuilder(String fieldName, String distance) {
        return QueryBuilders.geoDistanceQuery(fieldName)
                .distance(distance)
                .point(convertGeoPoint());
    }
}
